package com.dnbiz.api.sdk.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLConnection;

/**
 * <pre>
 * URL相关操作
 * - getURLContent 内容获取
 * </pre>
 * @author JWinder(2010-9-3)
 */
public class URLUtil {

	/**
	 * 通过URL远程连接读取信息
	 * @param url 远程URL
	 * @return url内容
	 * @throws IOException
	 * @author JWinder(2010-9-3)
	 */
	public static String getURLContent(final String url) throws IOException
	{
		return getURLContent(url, null);
	}
	
	/**
	 * 通过URL远程连接读取信息
	 * @param url 远程URL
	 * @param encoding InputStreamReader读取内容编码方式
	 * @return url内容
	 * @throws IOException
	 * @author JWinder(2010-9-3)
	 */
	public static String getURLContent(final String url, final String encoding) throws IOException
	{
		//1、通过URL远程连接url
		//2、读取url内容
		BufferedReader in = null;
		try {
			StringBuffer buf = new StringBuffer();
			
			java.net.URL murl = new java.net.URL(url);
			URLConnection urlCon = murl.openConnection();

			if(Validator.isNull(encoding))
			{
				in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
			} else {
				in = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), encoding));
			}
			
			String inputLine;
			
			while ((inputLine = in.readLine()) != null)
			{
				buf.append(inputLine);
			}
			
			return buf.toString();
		} catch (IOException e) {
			throw new IOException("连接URL[" + url + "]错误" + e.getMessage());
		} finally {
			if(null != in)
			{
				in.close();
			}
		}
	}
	

	/**
	 * 通过URL远程连接读取信息
	 * @param url 远程URL
	 * @param encoding InputStreamReader读取内容编码方式
	 * @return url内容
	 * @throws IOException
	 * @author JWinder(2010-9-3)
	 */
	public static byte[] getURLBytesContent(final String url, final String encoding) throws IOException
	{
		//1、通过URL远程连接url
		//2、读取url内容
		InputStream in = null;
		try {
			
			java.net.URL murl = new java.net.URL(url);
			URLConnection urlCon = murl.openConnection();
			in = urlCon.getInputStream();
			ByteArrayOutputStream bytestream = new ByteArrayOutputStream();  
			int ch;  
			while ((ch = in.read()) != -1) {  
			    bytestream.write(ch);  
			}  
			byte imgdata[] = bytestream.toByteArray();  
			bytestream.close();  
			return imgdata;  
			
		} catch (IOException e) {
			throw new IOException("连接URL[" + url + "]错误" + e.getMessage());
		} finally {
			if(null != in)
			{
				in.close();
			}
		}
	}
	
	public static void main(String[] args) throws IOException {
		System.out.println(getURLContent("http://who.godaddy.com/whois.aspx?domain=10231.com&prog_id=GoDaddy", "UTF-8"));
	}
}
